package top.deepdesigner.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import top.deepdesigner.pojo.DtsKeyword;
import top.deepdesigner.service.DtsKeywordService;

import java.util.Date;
import java.util.List;

/**
 * Start up <br/>
 * Created with IntelliJ IDEA. <br/>
 * Project Name: shop_manage <br/>
 * Author: duanruiqing <br/>
 * DateTime: 2022/9/24 星期六 15:09:27 <br/>
 */
@Service
public class DtsKeywordServiceImpl extends ServiceImpl<BaseMapper<DtsKeyword>, DtsKeyword> implements DtsKeywordService {
  @Override
  public Long getKeywordCount() {
    return this.count(new LambdaQueryWrapper<DtsKeyword>().eq(DtsKeyword::getDeleted, false));
  }

  @Override
  public List<DtsKeyword> getKeywordList(Integer page, Integer limit, String sort, String order, String keyword, String url) {
    QueryWrapper<DtsKeyword> wrapper = new QueryWrapper<>();
    wrapper.eq(true, "deleted", false)
        .like(!StringUtils.isEmpty(keyword), "keyword", keyword)
        .like(!StringUtils.isEmpty(url), "url", url)
        .orderBy(!StringUtils.isEmpty(sort), "asc".equalsIgnoreCase(order), sort);
    return this.page(new Page<>(page, limit), wrapper).getRecords();
  }

  @Override
  @Transactional
  public DtsKeyword createKeyword(DtsKeyword keyword) {
    List<DtsKeyword> list = this.list(new LambdaQueryWrapper<DtsKeyword>().eq(DtsKeyword::getDeleted, false).eq(DtsKeyword::getKeyword, keyword.getKeyword()));
    if (list.size() > 0) {
      return null;
    }
    keyword.setAddTime(new Date());
    keyword.setUpdateTime(new Date());
    keyword.setDeleted(false);
    this.save(keyword);
    return keyword;
  }

  @Override
  @Transactional
  public DtsKeyword updateKeyword(DtsKeyword keyword) {
    keyword.setUpdateTime(new Date());
    LambdaQueryWrapper<DtsKeyword> wrapper = new LambdaQueryWrapper<>();
    wrapper.eq(DtsKeyword::getId, keyword.getId());
    this.update(keyword, wrapper);
    return keyword;
  }

  @Override
  @Transactional
  public void deleteKeyword(DtsKeyword keyword) {
    keyword.setDeleted(true);
    LambdaQueryWrapper<DtsKeyword> wrapper = new LambdaQueryWrapper<>();
    wrapper.eq(DtsKeyword::getId, keyword.getId());
    this.update(keyword, wrapper);
  }
}
